package com.example.qinghe.frontController.frontmeeting;

import cn.hutool.core.io.FileUtil;
import com.example.qinghe.entity.Common;
import com.example.qinghe.entity.meeting.Attachs;
import com.example.qinghe.entity.meeting.Mattendance;
import com.example.qinghe.entity.meeting.Meeting;
import com.example.qinghe.entity.meeting.Meetingroom;
import com.example.qinghe.service.communication.StaffService;
import com.example.qinghe.service.meeting.AttachsService;
import com.example.qinghe.service.meeting.MattendanceService;
import com.example.qinghe.service.meeting.MeetingService;
import com.example.qinghe.service.meeting.MeetingroomService;
import com.example.qinghe.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/front/meeting")
@Api(tags = "会议系统->会议管理", description = "FrontMeetingController")
public class FrontMeetingController {

    @Autowired
    private MeetingroomService meetingroomService;

    @Autowired
    private MattendanceService mattendanceService;

    @Autowired
    private AttachsService attachsService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private MeetingService service;


    @Value("${upload-path}")
    private String pathloc;


    @ApiOperation("新建会议，涉及会议主持人、演讲嘉宾、参会人等涉及人员字段，请返回对应人员id")
    @PostMapping("/addManager")
    public Result meetingadd(@RequestBody Meeting meeting, HttpServletRequest request) {
        int insert = service.meetingadd(meeting);
        return insert > 0 ? Result.success("添加成功") : Result.error("添加失败");
    }

    @ApiOperation("查询所有已有会议的信息,包含会议室信息,meetingroomInfo为对应会议室信息")
    @GetMapping("/meetingListAll")
    public Result meetingListAll() {
        List<Meeting> meetingList = service.getMeetingIncludeRoom();
        System.out.println(">>>>>>>>>" + meetingList);
        if (meetingList == null) {
            return Result.error("没有找到");
        }
        return Result.success(meetingList, "已全部找出");
    }


//    @ApiOperation("查询所有已有会议的信息,list集合，以分号(;)为分隔")
//    @GetMapping("/meetingListAll")
//    public Result meetingListAll(){
//        List<Meeting> meetings = service.selectAll();
//        List<Object> objectList=new ArrayList<>();
//        for (Meeting meeting : meetings) {
//            Long id = meeting.getId();
//            Meeting mt = service.selectById(id);
//            objectList.add(mt);
//            Long meetingroomId = meeting.getMeetingroomId();
//            Meetingroom meetingroom = meetingroomService.SelectMeetingroomById(meetingroomId);
//           objectList.add(meetingroom);
//           objectList.add(";");
//        }
//        return Result.success(objectList,"已全部找出");
//    }


    @ApiOperation("查询单个会议的所有信息")
    @GetMapping("/meetingListOne/{id}")
    public Result meetingListOne(@PathVariable(value = "id") Long id) {
        List<Object> objectList = new ArrayList<>();
        Meeting meeting = service.selectById(id);
        objectList.add(meeting);
        Long meetingroomId = meeting.getMeetingroomId();
        Meetingroom meetingroom = meetingroomService.SelectMeetingroomById(meetingroomId);
        objectList.add(meetingroom);
        if (objectList == null) {
            return Result.error("没有找到");
        }
        return Result.success(objectList, "找到了");
    }

    @ApiOperation("查询单个会议的的开会地址")
    @GetMapping("/meetingListOnePlace/{id}")
    public Result meetingListOnePlace(@PathVariable(value = "id") Long id) {
        Meeting meeting = service.selectById(id);
        Long meetingroomId = meeting.getMeetingroomId();
        Meetingroom meetingroom = meetingroomService.SelectMeetingroomById(meetingroomId);
        if (meetingroom == null) {
            return Result.error("没有找到");
        }
        return Result.success(meetingroom, "找到了");
    }


    @ApiOperation("根据会议id，查询单个会议的签到信息,count为应签到人数，counted为已签到人数")
    @GetMapping("/mattend/{id}")
    public Result selectMattendInfo(@PathVariable(value = "id") Long id) {

        //获取签到表中 签到人员的信息
        List<Mattendance> mat = new ArrayList<>();
        //List<Mattendance> mattendances = service.selectMattendInfoByMeetingId(id);
        List<Mattendance> mattendances = mattendanceService.selectMattendsInfo(id);
        for (Mattendance mattendance : mattendances) {
            String aName = mattendance.getAName();
            Common sttInfo = staffService.sel(Long.parseLong(aName));
            String name = (String) sttInfo.get("name");
            mattendance.setAName(name);
            mat.add(mattendance);
        }
        if (mat == null) {
            return Result.error("没有找到");
        }
       // System.out.println("会议签到信息" + mat);
        //获取会议室图片地址
        String img = service.selectImgById(id);
        //获取参会人员id字符串
        String attendees = service.selectAttendeesById(id); //selectAttendeesById
        String[] numbers = attendees.split("\\,"); // 以逗号为分隔符分割字符串
        List<Object> result = new ArrayList<>();
        for (String num : numbers) {
            if (!num.isEmpty()) {
                String s = num.trim();
                Common sttInfo = staffService.sel(Long.parseLong(s));
                result.add(sttInfo);
//                String name = (String)sttInfo.get("name");
//                if (name==null) {
//                    name="员工";
//                }
//                result.add(name);
//                String phone = (String)sttInfo.get("phone");
//                if (phone==null) {
//                    phone="没有手机号";
//                }
//                result.add(phone);
            }
        }


        //应签到人数
        int count = result.size();
        //System.out.println("应签到人数"+count);
        //已签到人数
        int counted = service.countAttendedByMeetingId(id);
        return Result.success(mat, img, count, counted);
    }

    @ApiOperation("根据会议id查询会议的参会人信息")
    @GetMapping("/attendee/{id}")
    public Result selectAttendeeInfo(@PathVariable(value = "id") Long id) {

        String attendees = service.selectAttendeesById(id);
        String[] numbers = attendees.split("\\,"); // 以逗号为分隔符分割字符串
        // Map<String,List<String>> attMap =new HashMap<>();
        List<Object> objectList = new ArrayList<>();
        List<String> result = new ArrayList<>();

        for (String num : numbers) {
            if (!num.isEmpty()) {
                String s = num.trim();
                long att = Long.parseLong(s);
                Common sttInfo = staffService.sel(att);
                objectList.add(sttInfo);
//                String name = (String)sttInfo.get("name");
//                result.add(name);
//                String phone = (String)sttInfo.get("phone");
//                result.add(phone);
//                String img = (String)sttInfo.get("img");

                // result.add(img);
                //放入大map
                // attMap.put("所有参会人的信息",result);

            }
        }
        return Result.success(objectList);
    }

    @ApiOperation("查询会议联系人的电话、邮箱等联系方式")
    @GetMapping("/contact/{id}")
    public Result meetingContact(@PathVariable(value = "id") Long id) {
        List<String> infoList = new ArrayList<>();
        Meeting meeting = service.selectById(id);
        String contact = meeting.getContact();
        if (contact == null || contact == "") {
            return Result.error("没有找到会议联系人");
        }
        long contactId = Long.parseLong(contact);
        //调用staff 方法，获取id对应 的手机号，email
        Common speaker = staffService.sel(contactId);
        String name = (String) speaker.get("name");
        infoList.add(name);
        String img = (String) speaker.get("img");
        infoList.add(img);
        String phone = (String) speaker.get("phone");
        infoList.add(phone);
        String email = (String) speaker.get("email");
        infoList.add(email);
        if (infoList == null) {
            return Result.error("没有找到");
        }
        return Result.success(infoList);
    }


    /**
     * 提供会议附件 链接地址
     */
    @ApiOperation("提供会议id，查询会议附件的链接地址，提供给前端存储路径给前端，多文件则为字符串数组 ")
    @GetMapping("/{id}")
    public Result meetingDataUrl(@PathVariable(value = "id") Long id) {
        // List<String> listUrl=new ArrayList<>();
        Meeting meeting = service.selectById(id);
        String meetingDatas = meeting.getMeetingData();
        if (meetingDatas == null) {
            return Result.error("没有附件");
        }
        return Result.success(meetingDatas, "scuess");
    }

//    public Result meetingDataUrl(@PathVariable(value = "id") Long id){
//       // List<String> listUrl=new ArrayList<>();
//        Map<String,String> map=new HashMap<>();
//        List<Attachs> attachs = attachsService.selectByMetId(id);
//        for (Attachs attach : attachs) {
//            String url = attach.getAttachLocation();
//            String attachName = attach.getAttachName();
//            map.put(attachName,url);
//        }
//
//        return Result.success(map);
//    }


    /**
     * 多文件上传
     */

    @ApiOperation("文件上传,若多文件上传，前端多次调用此接口，返回文件地址数组字符串，存入数据库")
    @PostMapping("/uploadfile")
    public Result upload(MultipartFile file) throws IOException {

        //获取当前项目的路径   d:temp\files
        String ROOT_PATH = pathloc + File.separator + "files";

        String originalFilename = file.getOriginalFilename(); //文件的原始名称   aaa.jpg
        String mainName = FileUtil.mainName(originalFilename); //不包含后缀的文件名 aaa
        String extName = FileUtil.extName(originalFilename); //文件后缀  jpg
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);  // 如果当前文件的父级目录不存在，就创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {  // 如果当前上传的文件已经存在了，那么这个时候我就要重名一个文件名称
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去
        String url = "http://localhost:8020/front/meeting/download/" + originalFilename;
        return Result.success(url);//返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是我的后台提供出来的
    }


//    public Result upLoadFile(@RequestParam("file") MultipartFile[] files, @Param("id") Long id){
//        //创建附件表对象
//        Attachs attachs = new Attachs();
//        List<Attachs> listAtt=new ArrayList<>();
//        //判断文件是否存在
//        for (MultipartFile file:files){
//            try {
//                String newFileName="";
//                String filename="";
//                if (!file.isEmpty()) {
//                     filename = file.getOriginalFilename();    // aaa.doc
//
//                    newFileName = filename.substring(filename.lastIndexOf(".") ); //.doc
//                }
//                newFileName= UUID.randomUUID().toString()+newFileName; //djsadf.doc
//
//                String path=pathloc+ File.separator+newFileName; // d:temp/dssdf.doc
//
//                File newfile = new File(path);
//                if (!newfile.exists()) {
//                    //这里用到了mkdirs 创建多层目录
//                    newfile.mkdirs();
//                }
//                file.transferTo(newfile);
//
//                //本地目录
//                String url1="img"+File.separator+newFileName;  // d:temp/dssdf.doc   img/dssdf.doc    listset img("http:loclhoiat
//                //路径存入附件表
//
//                System.out.println("filename="+filename);
//                attachs.setAttachName(filename);
//                System.out.println("----------"+url1);
//                attachs.setAttachLocation(url1);
//                attachs.setMId(id);
//                int count = attachsService.insertAttach(attachs);
//                listAtt.add(attachs);
//                if (count!=1) {
//                    return Result.error("上传失败！");
//                }
//
//                //下载路径
//                String url2="http://localhost:8020/meeting/download"+newFileName;
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return Result.success(listAtt,"上传成功");
    //  }


    /**
     * 预览会议资料
     * @param
     * @return
     */
//    @ApiOperation("预览会议资料")
//    @GetMapping  ("/scan/{fileName}")
//    public void download2(@PathVariable String fileName, HttpServletResponse response) throws IOException {
//        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览
//        String  ROOT_PATH = pathloc+File.separator+"img";  //   d:temp/files
//        String filePath = ROOT_PATH  + File.separator + fileName;
//        if (!FileUtil.exist(filePath)) {
//            return;
//        }
//        byte[] bytes = FileUtil.readBytes(filePath);
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(bytes);  // 数组是一个字节数组，也就是文件的字节流数组
//        outputStream.flush();
//        outputStream.close();
//    }


    /**
     * 下载会议资料
     *
     * @param fileName
     * @return
     */
    @ApiOperation("下载会议资料，前端传递文件名称")
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 附件下载

        String ROOT_PATH = pathloc + File.separator + "files";  //   d:temp/files
        String filePath = ROOT_PATH + File.separator + fileName; //  d:temp/files/aaa.jpg
        if (!FileUtil.exist(filePath)) {
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);  // 数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();
        outputStream.close();
    }


    @ApiOperation("查询会议演讲嘉宾的信息")
    @GetMapping("/speakers/{id}")
    public Result meetingSpeaker(@PathVariable(value = "id") Long id) {
        List<String> infoList = new ArrayList<>();
        Meeting meeting = service.selectById(id);
        String guestSpeakers = meeting.getGuestSpeakers();
        long speakerId = Long.parseLong(guestSpeakers);

        if (guestSpeakers == null || guestSpeakers == "") {
            return Result.error("没有演讲嘉宾或嘉宾为外聘");
        }
        //调用staff 方法，获取id对应 的手机号，email等
        Common speaker = staffService.sel(speakerId);
        String name = (String) speaker.get("name");
        infoList.add(name);
        String img = (String) speaker.get("img");
        infoList.add(img);
        String phone = (String) speaker.get("phone");
        infoList.add(phone);
        if (infoList == null) {
            return Result.error("没有找到");
        }
        return Result.success(infoList);
    }

}
